package com.cqupt.sendMes.task;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.cqupt.sendMes.entity.Task;
import com.cqupt.sendMes.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class ScheduledTask {

    @Autowired
    private TaskService taskService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 预置一个时间格式
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss");
    @Scheduled(cron = "0 0/5 * * * ?") // 每隔5分钟检查一次
    public void checkAndExecuteTasks() {
        // 获取当前时间
        LocalTime now = LocalTime.now();
        // 从 Redis 获取所有任务
        Set<String> tasks = stringRedisTemplate.keys("task.*");
        if (CollUtil.isNotEmpty(tasks)) {
            log.info("当前时间：{}，待执行任务数量：{}", now, tasks.size());

            // 遍历任务
            for (String taskId : tasks) {
                // 从 Redis 获取任务的执行时间
                String executeTimeStr = stringRedisTemplate.opsForValue().get(taskId);
                if(StrUtil.isBlank(executeTimeStr)){
                    continue;
                }
                LocalTime executeTime = LocalTime.parse(executeTimeStr, formatter);
                if (now.isAfter(executeTime) || now.equals(executeTime)) {
                    // 执行任务
                    Task task = taskService.getTaskById(Integer.valueOf(taskId.split("\\.")[1]));
                    if (ObjectUtil.isNotEmpty(task)) {
                        //TODO：执行任务逻辑
                        log.info("执行任务：{}", task);
                        // 从 Redis 中删除任务
                        redisTemplate.delete(taskId);
                    }
                }
            }
        } else {
            log.info("当前时间：{}，没有待执行任务", now);
        }
    }

    @Scheduled(cron = "0 0 0 * * ?") // 每天凌晨0点执行
    public void syncTasksToRedis() {
        /*
          每天凌晨从数据库同步到 Redis
         */
        List<Task> tasks = taskService.getTaskList();
        log.info("同步任务数量：{}", tasks.size());
        for (Task task : tasks) {
            redisTemplate.opsForValue().set("task."+task.getId(), task.getExecutionTime().format(formatter));
        }
    }

    @PostConstruct
    public void init() {
        log.info("开始初始化同步");
        syncTasksToRedis();
    }

}
